package lucene;

import java.io.IOException;
import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.WhitespaceTokenizer;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.index.Payload;

public class PayloadDemo {

	class BoldAnalyzer extends Analyzer {

		@Override
		public TokenStream tokenStream(String fieldName, Reader reader) {
			TokenStream result = new WhitespaceTokenizer(reader);
			result = new BoldFilter(result);
			return result;
		}
	}

	static class BoldFilter extends TokenFilter {
		public static int IS_NOT_BOLD = 0;
		public static int IS_BOLD = 1;
		private TermAttribute termAtt;
		private PayloadAttribute payloadAtt;

		protected BoldFilter(TokenStream input) {
			super(input);
			termAtt = addAttribute(TermAttribute.class);
			payloadAtt = addAttribute(PayloadAttribute.class);
		}

		@Override
		public boolean incrementToken() throws IOException {
			if (input.incrementToken()) {
				final char[] buffer = termAtt.termBuffer();
				final int length = termAtt.termLength();
				String tokenstring = new String(buffer, 0, length);
				if (tokenstring.startsWith("") && tokenstring.endsWith("")) {
					tokenstring = tokenstring.replace("", "");
					tokenstring = tokenstring.replace("", "");
					termAtt.setTermBuffer(tokenstring);
					payloadAtt.setPayload(new Payload(int2bytes(IS_BOLD)));
				} else {
					payloadAtt.setPayload(new Payload(int2bytes(IS_NOT_BOLD)));
				}
				return true;
			} else
				return false;
		}

		public static int bytes2int(byte[] b) {
			int mask = 0xff;
			int temp = 0;
			int res = 0;
			for (int i = 0; i < 4; i++) {
				res <<= 8;
				temp = b[i] & mask;
				res |= temp;
			}
			return res;
		}

		public static byte[] int2bytes(int num) {
			byte[] b = new byte[4];
			for (int i = 0; i < 4; i++) {
				b[i] = (byte) (num >>> (24 - i * 8));
			}
			return b;
		}
	}
}
